package errors

import (
	"fmt"
	kratosErrors "github.com/go-kratos/kratos/v2/errors"
)

type HTTPError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

func (e *HTTPError) Error() string {
	return fmt.Sprintf("HTTPError code: %d , message: %s ", e.Code, e.Message)
}

func NewHTTPError(code int, message string) *HTTPError {
	return &HTTPError{Code: code, Message: message}
}

func FromError(err error) *HTTPError {
	if err == nil {
		return nil
	}
	if se := new(HTTPError); kratosErrors.As(err, &se) {
		return se
	}
	if se := new(kratosErrors.Error); kratosErrors.As(err, &se) {
		return NewHTTPError(int(se.Code), se.Message)
	}
	return &HTTPError{Code: 500, Message: err.Error()}
}
